package org.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Set;

public class HashDemo {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try (Jedis jedis = jedisPool.getResource()) {
            //清空redis数据库
            jedis.flushAll();
            //以下为测试方法
            //testHsetAndHget(jedis);
            //testHexistsAndHdel(jedis);
            //testHkeysAndHvalues(jedis);
            //testHmget(jedis);
            //testHIncrByAndHincrByFloat(jedis);
        }
    }
    private static void testHsetAndHget(Jedis jedis) {
        System.out.println("测试 hset and hget");
        jedis.hset("key", "name", "zhangsan");
        jedis.hset("key", "age", "20");
        String name = jedis.hget("key", "name");
        System.out.println(name);
        String age = jedis.hget("key", "age");
        System.out.println(age);
    }
    private static void testHexistsAndHdel(Jedis jedis) {
        System.out.println("测试hexists 和 hdel");
        jedis.hset("key", "name", "zhangsan");
        boolean ok = jedis.hexists("key", "name");
        System.out.println(ok);
        jedis.hdel("key", "name");
        ok = jedis.hexists("key", "name");
        System.out.println(ok);
    }
    private static void testHkeysAndHvalues(Jedis jedis) {
        System.out.println("测试 hkeys 和 hvalues");
        jedis.hset("key", "name", "zhangsan");
        jedis.hset("key", "age", "20");
        Set<String> keys = jedis.hkeys("key");
        System.out.println(keys);
        List<String> values = jedis.hvals("key");
        System.out.println(values);
    }
    private static void testHmget(Jedis jedis) {
        System.out.println("测试 hmget");
        jedis.hset("key", "name", "zhangsan");
        jedis.hset("key", "age", "20");
        List<String> values = jedis.hmget("key", "name", "age");
        System.out.println(values);
    }
    private static void testHlen(Jedis jedis) {
        System.out.println("测试 hlen");
        jedis.hset("key", "name", "zhangsan");
        jedis.hset("key", "age", "20");
        long n = jedis.hlen("key");
        System.out.println(n);
    }
    private static void testHIncrByAndHincrByFloat(Jedis jedis) {
        System.out.println("测试 hincrby 与 hincrbyfloat");
        jedis.hset("key", "age", "20");
        long n = jedis.hincrBy("key", "age", 10);
        System.out.println(n);
        String value = jedis.hget("key", "age");
        System.out.println(value);
        double dn = jedis.hincrByFloat("key", "age", 0.5);
        System.out.println(dn);
        value = jedis.hget("key", "age");
        System.out.println(value);
    }
}
